package com.zzyl.job;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.zzyl.constant.CacheConstants;
import com.zzyl.entity.AlertRule;
import com.zzyl.mapper.AlertRuleMapper;
import com.zzyl.service.AlertRuleService;
import com.zzyl.vo.DeviceDataVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.util.List;

/**
 * @Description AlertJob
 * @Author dingyanchi
 * @Date 2025-01-02
 */
@Component
public class AlertJob {

    @Autowired
    private AlertRuleMapper alertRuleMapper;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    private AlertRuleService alertRuleService;

    @Scheduled(cron = "0 * * * * ?")
    public void deviceData(){
        //查询所有规则
        List<AlertRule> alertRuleVos = alertRuleMapper.selectByFunctionId(null, null, null);
        if (ObjectUtil.isEmpty(alertRuleVos)){
            return;
        }
        //查询所有设备上报的数据
        String data = redisTemplate.opsForValue().get(CacheConstants.DEVICE_LASTDATA_CACHE_KEY);
        if (ObjectUtil.isEmpty(data)){
            return;
        }
        //数据格式标准化处理
        //将上报数据转成List<DeviceDataVo>
        List<DeviceDataVo> list = JSONUtil.toList(data, DeviceDataVo.class);
        //对每条数据进行规则校验
        list.forEach(rule ->{
            alertRuleService.checkRules(rule);
        });



    }
}

